<?php

namespace backend\modules\rbac\controllers;

use backend\modules\rbac\models\AuthAssignment;
use backend\modules\rbac\models\AuthItem;
use backend\modules\rbac\models\AuthItemChild;
use backend\modules\rbac\models\Permission;
use mdm\admin\models\Route;
use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * RoleController implements the CRUD actions for AuthItem model.
 */
class PermissionController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all AuthItem models.
     * @return mixed
     */
    public function actionIndex()
    {
        $model = new Permission();
        $attributes = Yii::$app->request->get('Permission',[]);
        $attributes = array_filter($attributes);
        $attributes['type'] = AuthItem::TYPE_PERMISSION;
        if(Yii::$app->request->isAjax){
            $query = Permission::find()->where($attributes);
            $countQuery = clone $query;
            $data = $query->offset((Yii::$app->request->get('page') - 1) * Yii::$app->request->get('limit'))
                ->limit(Yii::$app->request->get('limit'))
                ->all();
            return [
                'code'=>0,
                'msg'=>'',
                'count'=>$countQuery->count(),
                'data'=>$data
            ];
        }
        if($attributes){
            $model->setAttributes($attributes);
        }
        return $this->render('index', [
            'model' => $model,
        ]);
    }

    /**
     * Displays a single AuthItem model.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);

        $routes = [];

        return $this->render('view', [
            'model' => $model,
            'routes' => $routes,
        ]);
    }

    /**
     * Creates a new AuthItem model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Permission();
        $model->type = AuthItem::TYPE_PERMISSION;

        if(Yii::$app->request->isAjax){
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return [
                    'status'=>200,
                    'msg'=>''
                ];
            }else{
                return [
                    'status'=>500,
                    'msg'=>'保存失败'
                ];
            }
        }
        $routes = $this->_getRoutes();
        return $this->render('create', [
            'model' => $model,
            'routes' => $routes,
        ]);
    }

    /**
     * Updates an existing AuthItem model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if(Yii::$app->request->isAjax){
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return [
                    'status'=>200,
                    'msg'=>''
                ];
            }else{
                return [
                    'status'=>500,
                    'msg'=>'保存失败'
                ];
            }
        }
        $routes = [];

        return $this->render('update', [
            'model' => $model,
            'routes' => $routes,
        ]);
    }

    /**
     * Deletes an existing AuthItem model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        if(Yii::$app->request->isAjax){
            $model = $this->findModel($id);
            $bool = $model->delete();
            if($bool){
                AuthItemChild::deleteAll(['parent'=>$model->name]);
                AuthAssignment::deleteAll(['item_name'=>$model->name]);
                return [
                    'status'=>'200',
                    'msg'=>''
                ];
            }else{
                return [
                    'status'=>'500',
                    'msg'=>$model->getErrors()
                ];
            }
        }

        return $this->redirect(['index']);
    }

    /**
     * Finds the AuthItem model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return AuthItem the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Permission::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }

    private function _getRoutes()
    {
        $routes = [];
        $route = new Route();
        $route->invalidate();
        $available = $route->getRoutes()['available'];
        foreach ($available as $value){
            if(strpos($value, '*') === false){
                $routes[$value] = $value;
            }
        }
        return $routes;
    }
}
